﻿CREATE PROCEDURE [acms].[Post_GetById]
	@Id int,
	@VersionTimeStamp datetime
AS

	declare @versionId int

	if @VersionTimeStamp is null and exists (select null from Post_View where Id = @Id and StartDate is null and EndDate is null) begin
		--find pending version
		select *
		from Post_View 
		where Id = @Id
			and StartDate is null
			and EndDate is null 
	end
	else if @VersionTimeStamp is null begin
		--no pending version but pending version reqested select last version in que ie end date is null
		select *
		from Post_View 
		where Id = @Id
			and StartDate is not null
			and EndDate is null 
	end
	else begin
		--find version live at specified date time
		SELECT *
		FROM Post_View 
		Where Id = @Id
			and StartDate <= @VersionTimeStamp
			and IsNull(EndDate, dateadd(n, 1, @VersionTimeStamp)) >= @VersionTimeStamp
	end
RETURN 0;